import 'package:firebase_remote_config/firebase_remote_config.dart';

class ServiceConfHelper {
  static ServiceConfHelper? _singleton;

  factory ServiceConfHelper() {
    _singleton ??= ServiceConfHelper._();
    return _singleton!;
  }

  ServiceConfHelper._();

  static const chatFreeMessageCountKey = "free_message_count";
  static const freeChatModeKey = "free_chat_mode";
  static const cleanModeKey = "clean_mode";
  static const defaultVipSelectYearKey = "default_vip_select_year";

  int _freeMessageCount = 100;
  bool _isDefaultVipSelectYear = false;
  bool _isFreeChatMode = false;
  bool _isCleanMode = false;

  ///免费聊天数量
  int get freeMessageCount => _freeMessageCount;

  ///是否默认选择订阅年
  bool get isDefaultVipSelectYear => _isDefaultVipSelectYear;

  ///免费聊天模式
  bool get isFreeChatMode => _isFreeChatMode;

  ///审核模式
  bool get isCleanMode => _isCleanMode;

  void init() async {
    final remoteConf = FirebaseRemoteConfig.instance;
    await remoteConf.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(minutes: 1),
      minimumFetchInterval: const Duration(hours: 1),
    ));

    // ///设置默认值
    await remoteConf.setDefaults({
      chatFreeMessageCountKey: _freeMessageCount,
      freeChatModeKey: _isFreeChatMode,
      cleanModeKey: _isCleanMode,
      defaultVipSelectYearKey: _isDefaultVipSelectYear,
    });

    FirebaseRemoteConfig.instance.onConfigUpdated.listen((event) async {
      await remoteConf.activate();
      _refreshConf();
    });

    fetch();
  }

  void fetch() async {
    final remoteConfig = FirebaseRemoteConfig.instance;
    try {
      await remoteConfig.fetchAndActivate();
    } catch (e) {}
    _refreshConf();
  }

  void _refreshConf() {
    final remoteConfig = FirebaseRemoteConfig.instance;

    _freeMessageCount = remoteConfig.getInt(chatFreeMessageCountKey);
    _isFreeChatMode = remoteConfig.getBool(freeChatModeKey);
    _isCleanMode = remoteConfig.getBool(cleanModeKey);
    _isDefaultVipSelectYear = remoteConfig.getBool(defaultVipSelectYearKey);
  }
}
